<template>
  <div class="profile-container">
    <!--<el-card shadow="never" class="profile-card">-->
    <!--  &lt;!&ndash; 个人信息部分 &ndash;&gt;-->
    <!--  <div class="section-title">个人信息</div>-->
    <!--  <el-form-->
    <!--      :model="userForm"-->
    <!--      :rules="userRules"-->
    <!--      ref="userFormRef"-->
    <!--      label-width="100px"-->
    <!--      class="user-form"-->
    <!--  >-->
    <!--    <el-form-item label="头像">-->
    <!--      <el-upload-->
    <!--          class="avatar-uploader"-->
    <!--          action="/api/upload"-->
    <!--          :show-file-list="false"-->
    <!--          :on-success="handleAvatarSuccess"-->
    <!--          :before-upload="beforeAvatarUpload"-->
    <!--      >-->
    <!--        <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />-->
    <!--        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>-->
    <!--      </el-upload>-->
    <!--    </el-form-item>-->

    <!--    <el-form-item label="姓名" prop="name">-->
    <!--      <el-input v-model="userForm.name" placeholder="请输入姓名"></el-input>-->
    <!--    </el-form-item>-->

    <!--    <el-form-item label="手机号" prop="phone">-->
    <!--      <el-input v-model="userForm.phone" disabled></el-input>-->
    <!--    </el-form-item>-->

    <!--    <el-form-item label="性别" prop="sex">-->
    <!--      <el-radio-group v-model="userForm.sex">-->
    <!--        <el-radio label="男">男</el-radio>-->
    <!--        <el-radio label="女">女</el-radio>-->
    <!--      </el-radio-group>-->
    <!--    </el-form-item>-->

    <!--    <el-form-item label="身份证号" prop="id_number">-->
    <!--      <el-input v-model="userForm.id_number" placeholder="请输入身份证号"></el-input>-->
    <!--    </el-form-item>-->

    <!--    <el-form-item>-->
    <!--      <el-button type="primary" @click="submitUserForm">保存修改</el-button>-->
    <!--    </el-form-item>-->
    <!--  </el-form>-->
    <!--</el-card>-->

    <!-- 地址管理部分 -->
    <el-card shadow="never" class="address-card">
      <div class="section-title">地址管理</div>

      <el-button
          type="primary"
          :icon="Plus"
          @click="showAddressDialog(null)"
          class="add-address-btn"
      >
        新增地址
      </el-button>

      <el-table :data="addressList" style="width: 100%" border>
        <el-table-column prop="consignee" label="收货人" width="120" align="center"></el-table-column>
        <el-table-column label="性别" width="80">
          <template #default="{row}">
            {{ row.sex === '1' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" align="center"></el-table-column>
        <el-table-column label="地址">
          <template #default="{row}">
            {{ row.detail }}
          </template>
        </el-table-column>
        <el-table-column prop="label" label="标签" width="100" align="center"></el-table-column>
        <el-table-column label="默认地址" width="100" align="center">
          <template #default="{row}">
            <el-tag v-if="row.isDefault" type="success">默认</el-tag>
            <el-button
                v-else
                type="text"
                @click="setDefaultAddress(row.id)"
            >
              设为默认
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{row}">
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="showAddressDialog(row)"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                icon="el-icon-delete"
                @click="deleteAddress(row.id)"
                style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 地址编辑对话框 -->
    <el-dialog
        :title="addressDialog.title"
        v-model="addressDialog.visible"
        width="600px"
    >
      <el-form
          :model="addressForm"
          :rules="addressRules"
          ref="addressFormRef"
          label-width="100px"
      >
        <el-form-item label="收货人" prop="consignee">
          <el-input v-model="addressForm.consignee" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addressForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="详细地址" prop="detail">
          <el-input
              v-model="addressForm.detail"
              placeholder="请输入详细地址"
              type="textarea"
              :rows="2"
          ></el-input>
        </el-form-item>

        <el-form-item label="地址标签" prop="label">
          <el-select v-model="addressForm.label" placeholder="请选择标签">
            <el-option label="家" value="家"></el-option>
            <el-option label="公司" value="公司"></el-option>
            <el-option label="学校" value="学校"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="默认地址" prop="isDefault">
          <el-switch v-model="addressForm.isDefault"></el-switch>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitAddressForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {addAddress, getAddressList, updateAddress, del } from '@/api/addressBook'
import { getUserInfo, updateUserInfo} from '@/api/user'
import { Plus } from '@element-plus/icons-vue'

// 用户表单数据
const userForm = reactive({
  id: null,
  name: '',
  phone: '',
  sex: '',
  id_number: '',
  avatar: ''
})

// 用户表单验证规则
const userRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  id_number: [
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
})

// 表单引用
const userFormRef = ref(null)

// 加载用户信息
const loadUserInfo = async () => {
  try {
    // 从localStorage获取当前登录用户的手机号
    const userPhone = localStorage.getItem('userPhone')
    if (!userPhone) {
      ElMessage.warning('未找到登录信息，请重新登录')
      return
    }

    const res = await getUserInfo(userPhone)
    if (res.code === '200' && res.data) {
      Object.assign(userForm, res.data)
    } else {
      ElMessage.error(res.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 提交用户信息
const submitUserForm = async () => {
  try {
    await userFormRef.value.validate()
    await updateUserInfo(userForm)
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error('更新用户信息失败:', error)
  }
}

// 头像上传成功
const handleAvatarSuccess = (res) => {
  userForm.avatar = res.data.url
  ElMessage.success('头像上传成功')
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGorPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }

  return isJPGorPNG && isLt2M
}


/*地址操作*/
// 地址列表
const addressList = ref([])

// 地址对话框
const addressDialog = reactive({
  visible: false,
  title: '',
  isEdit: false
})

// 地址表单数据
const addressForm = reactive({
  id: null,
  consignee: '',
  sex: 1,
  phone: '',
  detail: '',
  label: '',
  isDefault: false
})

// 地址表单验证规则
const addressRules = reactive({
  consignee: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
})

//地址表单引用
const addressFormRef = ref(null)

// 加载地址列表
const loadAddressList = async () => {
  try {
    const res = await getAddressList()
    console.log("res.data=",res.data)
    if(res.code === '200'){
      addressList.value = res.data
    }else{
      ElMessage.error(res.msg || '获取地址列表失败')
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 显示地址对话框
const showAddressDialog = (address) => {
  if (address) {
    // 编辑地址
    addressDialog.title = '编辑地址'
    addressDialog.isEdit = true
    Object.assign(addressForm, {
      id: address.id,
      consignee: address.consignee,
      sex: address.sex === '1' ? 1 : 0,
      phone: address.phone,
      detail: address.detail,
      label: address.label,
      isDefault: address.isDefault === 1 ? true : false
    })
  } else {
    // 新增地址
    addressDialog.title = '新增地址'
    addressDialog.isEdit = false
    resetAddressForm()
  }
  addressDialog.visible = true
}

// 重置地址表单
const resetAddressForm = () => {
  Object.assign(addressForm, {
    id: null,
    consignee: '',
    sex: 1,
    phone: '',
    detail: '',
    label: '',
    isDefault: false
  })
}

// 提交地址表单
const submitAddressForm = async () => {
  try {
    await addressFormRef.value.validate()
    const submitForm = {
      ...addressForm,
      isDefault: addressForm.isDefault ? 1 : 0
    }
    if (addressDialog.isEdit) {
      console.log("updateForm=",submitForm)
      const res = await updateAddress(submitForm)
      if(res.code === '200'){
        ElMessage.success(res.data||'地址更新成功')
      }else{
        ElMessage.error(res.msg||'地址更新失败')
      }
    } else {
      const res = await addAddress(submitForm)
      if(res.code === '200'){
        ElMessage.success(res.data||'地址添加成功')
      }else{
        ElMessage.error(res.msg||'地址添加失败')
      }
    }

    addressDialog.visible = false
    await loadAddressList()
  } catch (error) {
    console.error('提交地址失败:', error)
  }
}

// 删除地址
const deleteAddress = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该地址吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await del(id)
    if(res.code === '200'){
      ElMessage.success('地址删除成功')
    }else{
      ElMessage.error(res.msg||'地址删除失败')
    }
    await loadAddressList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
    }
  }
}

// 设置默认地址
const setDefaultAddress = async (id) => {
  try {
    const submitForm = {
      id:id,
      isDefault: 1
    }
    const res = await updateAddress(submitForm)
    if(res.code === '200'){
      ElMessage.success('默认地址设置成功')
    }else{
      ElMessage.error(res.msg||'默认地址设置失败')
    }
    await loadAddressList()
  } catch (error) {
    console.error('设置默认地址失败:', error)
  }
}

// 初始化加载数据
onMounted(() => {
  // loadUserInfo() todo
  loadAddressList()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card,
.address-card {
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.user-form {
  max-width: 600px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.add-address-btn {
  margin-bottom: 15px;
}

/* 添加响应式布局 */
@media screen and (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }

  .user-form {
    max-width: 100%;
  }
}

/* 对话框底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>